import {ArgumentMetadata, BadRequestException, Injectable, PipeTransform} from "@nestjs/common";
import {ZodSchema} from "zod";

Injectable()
export class ZodValidationPipe implements PipeTransform {
    constructor(private readonly schema: ZodSchema) {

    }

    transform(value: any, metadata: ArgumentMetadata): any {
        try {
            // value是参数，this.schema进行校验
            return this.schema.parse(value)
        } catch (err) {
            // 如果parse失败则抛出错误，catch捕获
            throw new BadRequestException('validation failed.','参数格式不对');
        }
    }
}
